/**
 * 处理页面滚动动画的工具函数
 */

/**
 * 添加滚动时的元素显示动画
 * @param {string} selector - 要添加动画的元素选择器
 * @param {string} animationClass - 要添加的动画类名
 * @param {number} threshold - 触发阈值 (0-1)
 */
export const addScrollAnimation = (selector, animationClass, threshold = 0.2) => {
    const elements = document.querySelectorAll(selector);
    
    if (!elements.length) return;
    
    const observer = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          entry.target.classList.add(animationClass);
          observer.unobserve(entry.target);
        }
      });
    }, {
      threshold
    });
    
    elements.forEach(el => {
      observer.observe(el);
    });
  };
  
  /**
   * 初始化页面上所有的滚动动画
   */
  export const initScrollAnimations = () => {
    // 为不同的元素添加不同的动画
    addScrollAnimation('.section-header', 'fade-in');
    addScrollAnimation('.work-card', 'fade-in-up', 0.1);
    addScrollAnimation('.about-text', 'fade-in-left');
    addScrollAnimation('.about-skills', 'fade-in-right');
    addScrollAnimation('.timeline-item', 'fade-in-up', 0.1);
    addScrollAnimation('.skill-item', 'fade-in', 0.1);
  };
  
  /**
   * 平滑滚动到页面指定位置
   * @param {string} targetId - 目标元素ID
   * @param {number} offset - 偏移量（像素）
   */
  export const scrollToElement = (targetId, offset = 0) => {
    const target = document.getElementById(targetId);
    
    if (!target) return;
    
    const targetPosition = target.getBoundingClientRect().top + window.pageYOffset;
    
    window.scrollTo({
      top: targetPosition - offset,
      behavior: 'smooth'
    });
  };
  
  /**
   * 为元素添加打字机效果
   * @param {HTMLElement} element - 要添加效果的元素
   * @param {string} text - 要显示的文本
   * @param {number} speed - 每个字符的延迟（毫秒）
   */
  export const typewriterEffect = (element, text, speed = 100) => {
    if (!element) return;
    
    element.textContent = '';
    
    let i = 0;
    const timer = setInterval(() => {
      if (i < text.length) {
        element.textContent += text.charAt(i);
        i++;
      } else {
        clearInterval(timer);
      }
    }, speed);
  };
  
  /**
   * 视差滚动效果
   * @param {string} selector - 要应用视差效果的元素选择器
   * @param {number} speed - 视差速度因子（1为正常速度）
   */
  export const parallaxScroll = (selector, speed = 0.5) => {
    const elements = document.querySelectorAll(selector);
    
    if (!elements.length) return;
    
    window.addEventListener('scroll', () => {
      const scrollPosition = window.pageYOffset;
      
      elements.forEach(el => {
        const elTop = el.offsetTop;
        const elHeight = el.offsetHeight;
        
        if (scrollPosition > elTop - window.innerHeight && scrollPosition < elTop + elHeight) {
          const distance = scrollPosition - elTop;
          const translate = distance * speed;
          
          el.style.transform = `translateY(${translate}px)`;
        }
      });
    });
  };